<?php

namespace app\modules\admin\controllers;

use app\common\controllers\AccessController;
use app\modules\admin\forms\merchant\MerchantCredentialForm;
use app\modules\admin\forms\merchant\MerchantForm;
use app\modules\admin\forms\merchant\MerchantInfoForm;
use app\modules\admin\services\MerchantService;
use yii\base\UserException;

class MerchantController extends AccessController{

    public function actionSearch(){
        $merchant_name = \Yii::$app->getRequest()->get('merchant_name');
        $cat_id = \Yii::$app->getRequest()->get('cat_id');
        $status = \Yii::$app->getRequest()->get('status');
        $pagesize = \Yii::$app->getRequest()->get('pagesize');

        return [
            'list'=>MerchantService::search($merchant_name,$cat_id,$status,$page,$pagesize),
            'page'=>$page->Out()
        ];
    }

    //添加
    public function actionAdd(){
        $base_form = new MerchantForm();
        $info_form = new MerchantInfoForm();
        $account_form = new MerchantCredentialForm();

        $base_form->setScenario("create");
        $info_form->setScenario("create");
        $account_form->setScenario("create");
        $base_form->load(\Yii::$app->getRequest()->post('base'),'');
        $info_form->load(\Yii::$app->getRequest()->post('info'),'');
        $account_form->load(\Yii::$app->getRequest()->post('account'),'');

        if(MerchantService::create($base_form,$info_form,$account_form)){
           return "";
        }else{
            throw new UserException(MerchantService::getError());
        }
    }

    //编辑
    public function actionEdit(){
        $base_form = new MerchantForm();
        $info_form = new MerchantInfoForm();

        $base_form->setScenario("update");
        $info_form->setScenario("update");
        $base_form->load(\Yii::$app->getRequest()->post('base'),'');
        $info_form->load(\Yii::$app->getRequest()->post('info'),'');

        if(MerchantService::update($base_form,$info_form)){
            return "";
        }else{
            throw new UserException(MerchantService::getError());
        }
    }

    //获取信息
    public function actionGetInfoById($id){
        return MerchantService::getInfoById($id);
    }

    //更新状态
    public function actionUpdateStatus($id,$status)
    {
        MerchantService::updateStatusById($id,$status);
        return "";
    }

    //重置密码
    public function actionPassword(){
        $id = \Yii::$app->getRequest()->post('id');
        $password = \Yii::$app->getRequest()->post('password');
        if(MerchantService::password($id,$password)){
            return "";
        }else{
            throw new UserException(MerchantService::getError());
        }
    }
}